import React, { useEffect } from "react";
import { Layout, message } from "antd";
import { NavHeader, PageFooter } from "./components";
import "./App.scss";
import RouterBefore from "./router/RouterBefore";
import LoginForm from "./components/LoginForm";
import { getWhoAmIApi, getUserByIdApi } from "./api/user";
import { useDispatch } from "react-redux";
import { initUserInfo, changeLoginStatus } from "./redux/userSlice";

const { Header, Footer, Content } = Layout;
export default function App() {
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const dispatch = useDispatch();
  const token = localStorage.getItem("token");

  // 检查 token，保持登录状态
  useEffect(() => {
    const fetchUserToken = async () => {
      const res = await getWhoAmIApi();
      if (!res.data) {
        message.warning(res.msg);
        localStorage.removeItem("token");
      } else {
        // 有效 token -> 通过_id获得用户信息 -> 存到数据仓库
        message.success("欢迎回来~");
        const result = await getUserByIdApi(res.data._id);
        dispatch(initUserInfo(result.data));
        dispatch(changeLoginStatus(true));
      }
    };
    if (token) {
      fetchUserToken();
    }
  }, []);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleModalClose = () => {
    setIsModalOpen(false);
  };

  return (
    <>
      <Layout className="layout">
        <Header className="header">
          <NavHeader showModal={showModal} />
        </Header>
        <Content className="content">
          <RouterBefore />
        </Content>
        <Footer className="footer">
          <PageFooter />
        </Footer>
      </Layout>
      <LoginForm isModalOpen={isModalOpen} key={isModalOpen} onClose={handleModalClose} />
    </>
  );
}
